//
//  Settings_VC.m
//  Typical memes
//
//  Created by Denis Demjanko on 01.07.12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "Settings_VC.h"

@implementation Settings_VC


#pragma mark - View lifecycle

- (void)viewDidLoad{
    [super viewDidLoad];
    
    [self setTitle:@"Настройки"];

    scroller = [[MGScrollView alloc] initWithFrame:CGRectMake(0, 0, 320, 460)];
    scroller.alwaysBounceVertical = YES;
    scroller.delegate = self;
    [self.view addSubview:scroller];

    UIButton *back = [UIButton buttonWithType:UIButtonTypeCustom];
    [back setFrame:CGRectMake(0, 0, 53, 33)];
    [back setBackgroundImage:[UIImage imageNamed:@"Button (Back)"] forState:UIControlStateNormal];
    [back setBackgroundImage:[UIImage imageNamed:@"Button (Back)_1"] forState:UIControlStateHighlighted];
    [back addTarget:self action:@selector(onBack) forControlEvents:UIControlEventTouchUpInside];
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:back];
    
    [self addBoxes];
}

-(void)addBoxes{
    MGStyledBox *box_1 = [MGStyledBox box];
    box_1.tag = 5;
    
    MGBoxLine *header_box_1 = [MGBoxLine multilineWithText:@"Контролируйте загрузку изображений" font:[UIFont fontWithName:@"HelveticaNeue-Bold" size:16] padding:24.0f];
    [box_1.topLines addObject:header_box_1];
    
    UISwitch *switch_box_1 = [[UISwitch alloc] initWithFrame:CGRectZero];
    switch_box_1.on = [[NSUserDefaults standardUserDefaults] boolForKey:@"isSave"];
    [switch_box_1 addTarget:self action:@selector(onSaveImages) forControlEvents:UIControlEventValueChanged];
    
    MGBoxLine *line_box_1 = [MGBoxLine lineWithLeft:@"Сохранять изображения?" right:switch_box_1];
    [box_1.topLines addObject:line_box_1];
        
    MGBoxLine *line_box_2 = [MGBoxLine lineWithLeft:[NSString stringWithFormat:@"Считаю..."] right:nil];
    line_box_2.tag = 10;
    [box_1.topLines addObject:line_box_2];
    

    MGStyledBox *box_2 = [MGStyledBox box];
    
    MGBoxLine *header_box_2 = [MGBoxLine multilineWithText:@"Понравилось приложения? Проголосуйте за нас!" font:[UIFont fontWithName:@"HelveticaNeue-Bold" size:16] padding:24.0f];
    [box_2.topLines addObject:header_box_2];
    
    UIButton *star = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 36, 36)];
    [star setBackgroundImage:[UIImage imageNamed:@"star_gold.png"] forState:UIControlStateNormal];
    [star setBackgroundImage:[UIImage imageNamed:@"star_gold_1.png"] forState:UIControlStateHighlighted];
    [star addTarget:self action:@selector(onRate) forControlEvents:UIControlEventTouchUpInside];
    
    MGBoxLine *line_box_3 = [MGBoxLine lineWithLeft:@"Проголосовать" right:star];
    [box_2.topLines addObject:line_box_3];
    
    MGStyledBox *box_3 = [MGStyledBox box];
    
    MGBoxLine *header_box_3 = [MGBoxLine multilineWithText:@"У Вас появились вопросы или пожелания? Напишите нам!" font:[UIFont fontWithName:@"HelveticaNeue-Bold" size:16] padding:24.0f];
    [box_3.topLines addObject:header_box_3];
    
    UIButton *mail = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 36, 36)];
    [mail setBackgroundImage:[UIImage imageNamed:@"mail.png"] forState:UIControlStateNormal];
    [mail setBackgroundImage:[UIImage imageNamed:@"mail_1.png"] forState:UIControlStateHighlighted];
    [mail addTarget:self action:@selector(onMail) forControlEvents:UIControlEventTouchUpInside];
    
    MGBoxLine *line_box_4 = [MGBoxLine lineWithLeft:@"Написать письмо" right:mail];
    [box_3.topLines addObject:line_box_4];
    
    [scroller.boxes addObject:box_1];
    [scroller.boxes addObject:box_2];
    [scroller.boxes addObject:box_3];

    [scroller drawBoxesWithSpeed:0.6f];
    [scroller flashScrollIndicators];
    
    [self performSelectorInBackground:@selector(setNewSize) withObject:nil];

}

#pragma mark - IBActions

-(void)onRate{
    NSString* url = [NSString stringWithFormat:
					 @"http://itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?id=%@&pageNumber=0&sortOrdering=1&type=Purple+Software&mt=8", @"488108471"];
	[[UIApplication sharedApplication] openURL: [NSURL URLWithString: url]];
}

-(void)onMail{
    Class mailClass = (NSClassFromString(@"MFMailComposeViewController"));
	if (mailClass != nil){
		if ([mailClass canSendMail]){
			[self displayComposerSheet];
		}
		else{
			[self launchMailAppOnDevice];
		}
	}
	else{
		[self launchMailAppOnDevice];
	}
 
}

-(void)onTrash{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:@"Удалить все загруженные изображения?" delegate:self cancelButtonTitle:@"Отмена" otherButtonTitles:@"Удалить", nil];
    [alert show];
}

-(void)onBack{
    [[NSNotificationCenter defaultCenter] postNotificationName:@"SHOW_TAB_BAR" object:self];
    [self.navigationController popToRootViewControllerAnimated:YES];
}

-(void)onSaveImages{
    BOOL isSave = ![[NSUserDefaults standardUserDefaults] boolForKey:@"isSave"];
    
    [[NSUserDefaults standardUserDefaults] setBool:isSave forKey:@"isSave"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

#pragma mark - UIAlertView delegate

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if(buttonIndex==1){
        hud = [[MBProgressHUD alloc] initWithView:self.navigationController.view];
        [self.navigationController.view addSubview:hud];
        hud.dimBackground = YES;
        [hud show:YES];
        
        [self performSelector:@selector(deleteImages) withObject:nil afterDelay:0.5f];
    }
}

-(void)deleteImages{
    NSFileManager *fm = [NSFileManager defaultManager];
    NSString *directory =[NSHomeDirectory() stringByAppendingPathComponent:@"Library/Caches/ImageCache/"];
    NSError *error = nil;
    for (NSString *file in [fm contentsOfDirectoryAtPath:directory error:&error]) {
        [fm removeItemAtPath:[NSString stringWithFormat:@"%@/%@", directory, file] error:nil];
    }
    
    [hud hide:YES];
    [hud removeFromSuperview];
    hud = nil;
    
    [self performSelectorInBackground:@selector(setNewSize) withObject:nil];
}

#pragma mark - UIScrollViewDelegate (for snapping boxes to edges)

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    [(MGScrollView *)scrollView snapToNearestBox];
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView  willDecelerate:(BOOL)decelerate {
    if (!decelerate) 
        [(MGScrollView *)scrollView snapToNearestBox];
}

#pragma mark -
#pragma mark images size

-(void)setNewSize{
    MGStyledBox *box = (MGStyledBox*)[scroller viewWithTag:5];
    
    MGBoxLine *line_box = (MGBoxLine*)[box viewWithTag:10];
    [line_box removeFromSuperview];
    line_box = nil;
    
    UIButton *trash = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 36, 36)];
    [trash setBackgroundImage:[UIImage imageNamed:@"trash.png"] forState:UIControlStateNormal];
    [trash setBackgroundImage:[UIImage imageNamed:@"trash_1.png"] forState:UIControlStateHighlighted];
    [trash addTarget:self action:@selector(onTrash) forControlEvents:UIControlEventTouchUpInside];
    
    line_box = [MGBoxLine lineWithLeft:[NSString stringWithFormat:@"Загружено %@",[self getMPSize]] right:trash];
    line_box.tag = 10;
    [box.topLines replaceObjectAtIndex:2 withObject:line_box];
    
    [scroller drawBoxesWithSpeed:0.0f];
    [scroller flashScrollIndicators];
}

- (unsigned long long int)folderSize:(NSString *)folderPath {
    NSArray *filesArray = [[NSFileManager defaultManager] subpathsOfDirectoryAtPath:folderPath error:nil];
    NSEnumerator *filesEnumerator = [filesArray objectEnumerator];
    NSString *fileName;
    unsigned long long int fileSize = 0;
	
    while (fileName = [filesEnumerator nextObject]) {
        NSDictionary *fileDictionary = [[NSFileManager defaultManager] fileAttributesAtPath:[folderPath stringByAppendingPathComponent:fileName] traverseLink:YES];
        fileSize += [fileDictionary fileSize];
    } 
	
    return fileSize;
}

-(NSString *)getMPSize{
	NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"Library/Caches/ImageCache"];
    int app = [self folderSize:path];
    return [NSString stringWithFormat:@"%i МБ.",app/1024/1024];
}


#pragma mark Compose Mail

-(void)displayComposerSheet {
	MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
	picker.mailComposeDelegate = self;
	[picker setSubject:@"Типичные МЕМЫ - iPhone Application"];
	
	NSArray *toRecipients = [NSArray arrayWithObject:@"denis.d@it-dimension.com"]; 
	[picker setToRecipients:toRecipients];
	
	[self presentModalViewController:picker animated:YES];
}


- (void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error {	
	[self dismissModalViewControllerAnimated:YES];
}


-(void)launchMailAppOnDevice{
	NSString *recipients = @"mailto:denis.d@it-dimension.com&subject=Типичные МЕМЫ - iPhone Application";
	
	NSString *email = [NSString stringWithFormat:@"%@", recipients];
	email = [email stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
	
	[[UIApplication sharedApplication] openURL:[NSURL URLWithString:email]];
}

#pragma mark - Memory Management

- (void)didReceiveMemoryWarning{
    [super didReceiveMemoryWarning];
}

- (void)viewDidUnload{
    scroller = nil;
    [super viewDidUnload];
}

@end
